package jmu.zzh.alumnus.business.controller;

import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jmu.zzh.alumnus.business.entity.Donation;
import jmu.zzh.alumnus.business.request.DonationRequest;
import jmu.zzh.alumnus.business.service.DonationService;
import jmu.zzh.alumnus.common.response.R;
import jmu.zzh.alumnus.common.util.CustomJWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/donation")
public class DonationController {

    @Autowired
    private DonationService donationService;

    @Autowired
    private CustomJWTUtils customJWTUtils;

    @PostMapping
    public R<Integer> createDonation(@Valid @RequestBody DonationRequest request, HttpServletRequest httpRequest) {
        String authHeader = httpRequest.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.fail("未登录或token无效");
        }
        
        String token = authHeader.substring(7);
        if (!customJWTUtils.validate(token)) {
            return R.fail("token已过期或无效");
        }
        
        Long userId = customJWTUtils.getUserIdFromToken(token);
        if (userId == null) {
            return R.fail("用户信息无效");
        }
        
        return R.ok(donationService.createDonation(userId, request));
    }

    @GetMapping("my")
    public R<PageInfo<Donation>> getMyDonations(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.fail("未登录或token无效");
        }
        
        String token = authHeader.substring(7);
        if (!customJWTUtils.validate(token)) {
            return R.fail("token已过期或无效");
        }
        
        Long userId = customJWTUtils.getUserIdFromToken(token);
        if (userId == null) {
            return R.fail("用户信息无效");
        }
        
        return R.ok(donationService.getMyDonations(userId, page, size));
    }

    @GetMapping("list")
    public R<PageInfo<Donation>> getAllDonations(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        return R.ok(donationService.getAllDonations(page, size));
    }
} 